<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// 引入数据库类
require_once 'database.php';

// 设置时区
date_default_timezone_set('Asia/Shanghai');

// 创建数据目录
$dataDir = 'visitor_data';
if (!file_exists($dataDir)) {
    mkdir($dataDir, 0755, true);
}

// 创建照片目录
$photoDir = $dataDir . '/photos';
if (!file_exists($photoDir)) {
    mkdir($photoDir, 0755, true);
}

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('只支持POST请求');
    }
    
    // 获取POST数据
    $latitude = $_POST['latitude'] ?? null;
    $longitude = $_POST['longitude'] ?? null;
    $accuracy = $_POST['accuracy'] ?? null;
    $timestamp = $_POST['timestamp'] ?? null;
    $photoData = $_POST['photo'] ?? null;
    
    // 验证数据（位置和照片至少要有一个）
    $hasLocation = !empty($latitude) && !empty($longitude);
    $hasPhoto = !empty($photoData) || !empty($_FILES['photo']['tmp_name']);
    
    if (!$hasLocation && !$hasPhoto) {
        throw new Exception('缺少位置信息或照片数据');
    }
    
    // 生成唯一ID
    $recordId = uniqid('visitor_', true);
    
    // 处理照片数据
    $photoFileName = null;
    
    // 优先处理FormData格式的照片
    if (!empty($_FILES['photo']['tmp_name'])) {
        $uploadedFile = $_FILES['photo'];
        if ($uploadedFile['error'] === UPLOAD_ERR_OK) {
            $imageType = 'jpg'; // 默认为jpg
            $photoFileName = $recordId . '_photo.' . $imageType;
            $photoPath = $photoDir . '/' . $photoFileName;
            
            if (move_uploaded_file($uploadedFile['tmp_name'], $photoPath)) {
                // 照片保存成功
            } else {
                throw new Exception('照片保存失败');
            }
        }
    }
    // 如果没有FormData格式的照片，尝试处理base64格式
    elseif ($photoData) {
        // 解析base64图片数据
        if (preg_match('/^data:image\/(\w+);base64,/', $photoData, $matches)) {
            $imageType = $matches[1];
            $photoData = substr($photoData, strpos($photoData, ',') + 1);
            $photoData = base64_decode($photoData);
            
            if ($photoData === false) {
                throw new Exception('照片数据解码失败');
            }
            
            // 保存照片
            $photoFileName = $recordId . '.' . $imageType;
            $photoPath = $photoDir . '/' . $photoFileName;
            
            if (file_put_contents($photoPath, $photoData) === false) {
                throw new Exception('照片保存失败');
            }
        } else {
            throw new Exception('无效的照片数据格式');
        }
    }
    
    // 初始化数据库
    $db = new Database();
    
    // 准备访客数据
    $visitorData = [
        'id' => $recordId,
        'timestamp' => date('Y-m-d H:i:s'),
        'client_timestamp' => $timestamp,
        'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
        'referer' => $_SERVER['HTTP_REFERER'] ?? 'direct',
        'latitude' => $latitude ? floatval($latitude) : null,
        'longitude' => $longitude ? floatval($longitude) : null,
        'accuracy' => $accuracy ? floatval($accuracy) : null,
        'photo_filename' => $photoFileName
    ];
    
    // 保存到数据库
    $db->insertVisitor($visitorData);
    
    // 记录访问日志到数据库
    $logData = [
        'visitor_id' => $recordId,
        'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        'timestamp' => date('Y-m-d H:i:s'),
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
        'referer' => $_SERVER['HTTP_REFERER'] ?? 'direct'
    ];
    $db->insertAccessLog($logData);
    
    // 同时保存到JSON文件作为备份（可选）
    $visitorInfo = [
        'id' => $recordId,
        'timestamp' => date('Y-m-d H:i:s'),
        'client_timestamp' => $timestamp,
        'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
        'referer' => $_SERVER['HTTP_REFERER'] ?? 'direct',
        'location' => [
            'latitude' => $latitude ? floatval($latitude) : null,
            'longitude' => $longitude ? floatval($longitude) : null,
            'accuracy' => $accuracy ? floatval($accuracy) : null
        ],
        'photo_filename' => $photoFileName
    ];
    
    // 备份到JSON文件
    $individualFile = $dataDir . '/' . $recordId . '.json';
    file_put_contents($individualFile, json_encode($visitorInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    
    // 返回成功响应
    echo json_encode([
        'success' => true,
        'message' => '数据保存成功',
        'visitor_id' => $recordId,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    // 返回错误响应
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>